const { Sequelize, DataTypes } = require('sequelize');

// 创建数据库连接
const sequelize = new Sequelize('travel', 'travel', 'AzMGmAMDBd4GsD5W', {
  host: '101.42.8.87',
  dialect: 'mysql',
  port: 3306,
  dialectOptions: {
    charset: 'utf8mb4',
    collate: 'utf8mb4_unicode_ci'
  },
  define: {
    charset: 'utf8mb4',
    collate: 'utf8mb4_unicode_ci'
  }
});

// 用户模型
const initUserModel = require('./models/user');
const User = initUserModel(sequelize, DataTypes);

// 景点模型
const initSightModel = require('./models/sight');
const Sight = initSightModel(sequelize, DataTypes);

// 评论模型
const initCommentModel = require('./models/comment');
const Comment = initCommentModel(sequelize, DataTypes);

// 门票模型
const initTicketModel = require('./models/ticket');
const Ticket = initTicketModel(sequelize, DataTypes);

// 文章模型
const initArticleModel = require('./models/article');
const Article = initArticleModel(sequelize, DataTypes);

// 订单模型
const initOrderModel = require('./models/order');
const Order = initOrderModel(sequelize, DataTypes);

// 订单-门票关联模型
const initOrderTicketModel = require('./models/orderTicket');
const OrderTicket = initOrderTicketModel(sequelize, DataTypes);

// 设置评论模型关联
Comment.associate({ User, Sight });

// 为User和Sight添加反向关联
User.hasMany(Comment, {
  foreignKey: 'userId',
  as: 'comments'
});

Sight.hasMany(Comment, {
  foreignKey: 'sightId',
  as: 'comments'
});

// 设置门票模型关联
Ticket.associate({ Sight, Order, OrderTicket });
Sight.hasOne(Ticket, {
  foreignKey: 'sightId',
  as: 'ticket'
});

// 设置订单模型关联
Order.associate({ User, Ticket, OrderTicket });

// 设置订单-门票关联模型
OrderTicket.associate({ Order, Ticket });

// 为User添加反向关联到Order
User.hasMany(Order, {
  foreignKey: 'userId',
  as: 'orders'
});

// 设置文章模型关联
Article.associate({ User });
User.hasMany(Article, {
  foreignKey: 'authorId',
  as: 'articles'
});

module.exports = {
  sequelize,
  DataTypes,
  Op: Sequelize.Op,
  User,
  Sight,
  Comment,
  Ticket,
  Article,
  Order,
  OrderTicket
};